package com.dl.dw;

import com.dl.dw.vo.QuestionVO;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

public class LocalDataBox {
    static MMKV appLocalData;//除非被卸载，不然数据不会被清理
    static MMKV userLocalData;//切换用户时会被清理

    private static MMKV getAppLocalData() {
        if (appLocalData == null) {
            appLocalData = MMKV.mmkvWithID("app");//可加密
        }
        return appLocalData;
    }

    private static MMKV getUserLocalData() {
        if (userLocalData == null) {
            userLocalData = MMKV.mmkvWithID("user");//可加密
        }
        return userLocalData;
    }

    public static final ArrayList<QuestionVO> getQuestionList() {
        String categoryListStr = getAppLocalData().decodeString(
                "sp_key_question_list", "[]");

        ArrayList<QuestionVO> categoryList = GsonUtil.gson().fromJson(categoryListStr,
                new TypeToken<ArrayList<QuestionVO>>() {
                }.getType());
        if (categoryList == null) {
            categoryList = new ArrayList<>();
        }
        return categoryList;
    }

    /**
     * 保存首页类别列表(图文)，加子分类(图文)
     *
     */
    public static final void setQuestionList(List<QuestionVO> questionVOS) {
        String categoryListStr = GsonUtil.gson().toJson(questionVOS);
        getAppLocalData().encode("sp_key_question_list",
                categoryListStr);
    }

    public static final ArrayList<QuestionVO> getQuestion2List() {
        String categoryListStr = getAppLocalData().decodeString(
                "sp_key_question_list2", "[]");

        ArrayList<QuestionVO> categoryList = GsonUtil.gson().fromJson(categoryListStr,
                new TypeToken<ArrayList<QuestionVO>>() {
                }.getType());
        if (categoryList == null) {
            categoryList = new ArrayList<>();
        }
        return categoryList;
    }

    /**
     * 保存首页类别列表(图文)，加子分类(图文)
     *
     */
    public static final void setQuestion2List(List<QuestionVO> questionVOS) {
        String categoryListStr = GsonUtil.gson().toJson(questionVOS);
        getAppLocalData().encode("sp_key_question_list2",
                categoryListStr);
    }

    /**
     * 退出登录时调用
     */
    public static void clearAllUserLocalData() {
        getUserLocalData().clearAll();
    }

    public static void clearAll() {
        getUserLocalData().clearAll();
        getAppLocalData().clearAll();
    }
}
